package yaohua.main;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import yaohua.entity.Entity_help;
import yaohua.jsoup.Jsoup_help;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * 文献检索界面 因为在搜索界面判断即可判断数据是否可以搜索到会比较友好，所以在这个activity中就加入了逻辑功能的代码
 * 
 * @author yh
 * 
 */
public class SearchActivity extends Activity
	{

		ProgressDialog progressDialog;
		List<String> list;
		String result;
		private String language = "CN";// 中文或英文
		private String searchWay = "HZ";// 检索方式
		private String keyWord;// 关键词
		private String type = "%";// 题名类型
		private String queryWay = "1";// 查询方式
		private String max = "0";
		private String records = "20";
		private String order = "正题名";

		private String language_name = "txtWxlx";
		private String searchWay_name = "txtPY";
		private String keyWord_name = "txtTm";
		private String type_name = "txtLx";
		private String queryWay_name = "txtSearchType";
		private String max_name = "nMaxCount";
		private String records_name = "nSetPageSize";
		private String order_name = "cSortFld";

		private Spinner spinner;
		private RadioGroup bookType, searchWay_xml;
		private RadioButton chinese, west, timing, pingyin;
		private EditText search_word;
		private Button search;

		public static final String SEARCH = "http://202.207.182.100:8080/pft/wxjs/tmjs.asp";

		@Override
		protected void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				setContentView(R.layout.search);
				list = new ArrayList<String>();
				// 列表中添加菜单项
				list.add("前方一致");
				list.add("模糊查询");
				list.add("精确查询");
				// 找出组件
				bookType = (RadioGroup) findViewById(R.id.bookType);
				chinese = (RadioButton) findViewById(R.id.chinese);
				west = (RadioButton) findViewById(R.id.west);
				searchWay_xml = (RadioGroup) findViewById(R.id.searchWay);
				timing = (RadioButton) findViewById(R.id.timing);
				pingyin = (RadioButton) findViewById(R.id.pingyin);
				spinner = (Spinner) findViewById(R.id.query);
				search_word = (EditText) findViewById(R.id.search_word);
				search = (Button) findViewById(R.id.search);
				// 定义适配器
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
				// 为适配器设置下拉列表的菜单样式
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				spinner.setAdapter(adapter);

				// 为bookType绑定监听器
				bookType.setOnCheckedChangeListener(new BookTypeListener());
				// 为searchWay_xml绑定监听器
				searchWay_xml.setOnCheckedChangeListener(new SearchWay_xmlListener());
				// 为spinner绑定监听器
				spinner.setOnItemSelectedListener(new SpinnerListener());
				// 为search按钮绑定监听器
				search.setOnClickListener(new SearchListener());
			}

		@Override
		public boolean onOptionsItemSelected(MenuItem item)
			{
				new AlertDialog.Builder(this).setTitle("关于").setMessage("本程序为中北大学图书馆使用,欢迎您能向作者提供在使用过程中的bug,以方便作者进行修改.联系作者新浪微薄@耀华info")
						.show();
				return super.onOptionsItemSelected(item);
			}

		@Override
		public boolean onCreateOptionsMenu(Menu menu)
			{
				menu.add("关于");
				return super.onCreateOptionsMenu(menu);
			}

		public String getKeyWord()
			{
				return search_word.getText().toString();
			}

		/**
		 * bookType的监听器代码
		 * 
		 * @author yh
		 * 
		 */
		class BookTypeListener implements OnCheckedChangeListener
			{

				public void onCheckedChanged(RadioGroup arg0, int arg1)
					{
						if (arg1 == chinese.getId())
							{
								language = "CN";

							}
						else if (arg1 == west.getId())
							{
								language = "EN";

							}
					}

			}

		/**
		 * searchWay_xml的监听器代码
		 */
		class SearchWay_xmlListener implements OnCheckedChangeListener
			{

				public void onCheckedChanged(RadioGroup group, int checkedId)
					{
						if (checkedId == timing.getId())
							{
								searchWay = "HZ";
							}
						else if (checkedId == pingyin.getId())
							{
								searchWay = "PY";
							}

					}

			}

		/**
		 * spinner 监听器代码
		 */
		class SpinnerListener implements OnItemSelectedListener
			{

				public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
					{
						if (arg2 == 0)
							{
								queryWay = "1";
							}
						else if (arg2 == 1)
							{
								queryWay = "2";
							}
						else if (arg2 == 2)
							{
								queryWay = "3";
							}
					}

				public void onNothingSelected(AdapterView<?> arg0)
					{

					}

			}

		/**
		 * sreach按钮事件监听代码
		 */
		class SearchListener implements OnClickListener
			{

				public void onClick(View v)
					{

						progressDialog = ProgressDialog.show(SearchActivity.this, "正在查询", "请稍等...", false, true);
						new Thread(new Runnable()
							{

								public void run()
									{
										try
											{
												keyWord = getKeyWord();
												if (keyWord.equals(""))
													{
														Message msg = new Message();
														msg.arg1 = 1;
														handler.sendMessage(msg);
													}
												else
													{
														Entity_help entity_help = new Entity_help();
														HttpResponse httpResponse = entity_help.postResponse(SEARCH, language_name,
																language, searchWay_name, searchWay, keyWord_name, keyWord, type_name,
																type, queryWay_name, queryWay, max_name, max, records_name, records,
																order_name, order);
														// 没有网络的话，此处httpResponse==null
														if (httpResponse == null)
															{
																Message msg = new Message();
																msg.arg1 = -1;
																handler.sendMessage(msg);
															}
														// 服务器错误
														if (!entity_help.code200(httpResponse))
															{
																Message msg = new Message();
																msg.arg1 = -2;
																handler.sendMessage(msg);
															}
														entity_help.handleBook(httpResponse, handler, "tdborder4", 1, 6,2,6,
																progressDialog);
													}

											}

										catch (Exception e)
											{
												progressDialog.dismiss();
												e.printStackTrace();
											}
										finally
											{
												progressDialog.dismiss();
											}
									}

							}).start();

					}

				// 配合线程处理UI
				Handler handler = new Handler()
					{

						@Override
						public void handleMessage(Message msg)
							{
								super.handleMessage(msg);
								if (msg.arg1 == -1)
									{
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "网络连接不可用，请检查网络设置", Toast.LENGTH_SHORT).show();
										msg.arg1 = 0;
									}
								else if (msg.arg1 == 1)
									{
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "请输入搜索关键词", Toast.LENGTH_SHORT).show();
										msg.arg1 = 0;
									}
								else if(msg.arg1==-2)
									{
										progressDialog.dismiss();
										Toast.makeText(getApplicationContext(), "内部服务器错误", Toast.LENGTH_SHORT).show();
										msg.arg1 = 0;
									}
								else
									{
										Bundle bundle = msg.getData();
										ArrayList<String> books = bundle.getStringArrayList("books");
										ArrayList<String> dateList = bundle.getStringArrayList("list");
										ArrayList<Map<String,String>> newBooks=(ArrayList<Map<String, String>>) bundle.getSerializable("newBooks");
										result = bundle.getString("result");

										if (books.size() == 0)
											{
												Toast.makeText(getApplicationContext(), "没有任何记录", Toast.LENGTH_SHORT).show();
											}
										// 初始化listActivity的数据
										else
											{
												ArrayList<String> storeUrl = new Jsoup_help().getStoreUrl(result);
												Intent intent = new Intent();
												intent.putStringArrayListExtra("dateList", (ArrayList<String>) dateList);
												intent.putStringArrayListExtra("books", books);
												intent.putParcelableArrayListExtra("newBooks", (ArrayList<? extends Parcelable>) newBooks);
												intent.putExtra("result", result);
												intent.putExtra("language", language);
												intent.putExtra("searchWay", searchWay);
												intent.putExtra("keyWord", keyWord);
												intent.putExtra("queryWay", queryWay);
												intent.putStringArrayListExtra("storeUrl", storeUrl);
												intent.setClass(getApplicationContext(), SearchBooksActivity.class);
												startActivity(intent);
											}

									}

							}

					};
			}

	}
